package teacher;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/ExamDetailServlet")
public class ExamDetailServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int examId = Integer.parseInt(request.getParameter("exam_id"));
        HttpSession session = request.getSession();
        Integer teacherId = (Integer) session.getAttribute("teacher_id");

        if (teacherId == null) {
            response.sendRedirect("teacher_student.jsp");
            return;
        }

        Connectmysql conn = null;
        try {
            conn = new Connectmysql(
                    "jdbc:mysql://localhost:3306/exam",
                    "root",
                    "root",
                    "com.mysql.cj.jdbc.Driver"
            );

            if (conn.open()) {
                String sql = "SELECT e.*, c.course_name, " +
                        "(SELECT GROUP_CONCAT(cl.class_name SEPARATOR ', ') " +
                        " FROM exam_class ec " +
                        " JOIN class cl ON ec.class_id = cl.class_id " +
                        " WHERE ec.exam_id = e.exam_id) AS class_names " +
                        "FROM exam e " +
                        "JOIN course c ON e.course_id = c.course_id " +
                        "WHERE e.exam_id = ? AND e.teacher_id = ?";

                ResultSet rs = conn.executeSql(sql, new Object[]{examId, teacherId});

                if (rs.next()) {
                    StringBuilder json = new StringBuilder("{");
                    json.append("\"exam_id\":").append(rs.getInt("exam_id")).append(",")
                            .append("\"exam_name\":\"").append(escapeJson(rs.getString("exam_name"))).append("\",")
                            .append("\"course_name\":\"").append(escapeJson(rs.getString("course_name"))).append("\",")
                            .append("\"start_time\":\"").append(escapeJson(rs.getTimestamp("start_time").toString())).append("\",")
                            .append("\"end_time\":\"").append(escapeJson(rs.getTimestamp("end_time").toString())).append("\",")
                            .append("\"duration\":").append(rs.getInt("duration")).append(",")
                            .append("\"status\":").append(rs.getInt("status")).append(",");

                    // 获取关联的班级名称
                    String classNames = rs.getString("class_names");
                    json.append("\"class_names\":\"")
                            .append(escapeJson(classNames != null ? classNames : "未分配班级"))
                            .append("\",")
                            .append("\"description\":\"")
                            .append(escapeJson(rs.getString("description")))
                            .append("\"}");

                    response.setContentType("application/json;charset=UTF-8");
                    response.getWriter().print(json.toString());
                } else {
                    response.sendRedirect("teacher.jsp?section=exam&error=考试信息获取失败");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.sendRedirect("teacher.jsp?section=exam&error=数据库错误");
        } finally {
            if (conn != null) {
                conn.close();
            }
        }
    }

    private String escapeJson(String input) {
        if (input == null) return "";
        return input.replace("\\", "\\\\")
                .replace("\"", "\\\"")
                .replace("\b", "\\b")
                .replace("\f", "\\f")
                .replace("\n", "\\n")
                .replace("\r", "\\r")
                .replace("\t", "\\t");
    }
}